package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.DesignSchemeImage;
import com.ruoyi.system.mapper.CasesGenMapper;
import com.ruoyi.system.mapper.DesignSchemeImageMapper;
import com.ruoyi.system.service.CaseService;
import com.ruoyi.system.utils.BeanUtil;
import com.ruoyi.system.vo.CaseDetailVo;
import com.ruoyi.system.domain.CasesGen;
import com.ruoyi.system.domain.CasesGenExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CaseImpl extends ServiceImpl<CasesGenMapper, CasesGen>
        implements CaseService {
    @Resource
    private CasesGenMapper caseGenMapper;


    @Autowired
    private DesignSchemeImageMapper imageMapper;


    /**
     * 案例编辑
     *
     * @param caseDetailVo
     * @return
     */
    @Override
    @Transactional
    public boolean editCase(CaseDetailVo caseDetailVo) {
        CasesGen caseGen = new CasesGen();
        BeanUtils.copyProperties(caseDetailVo, caseGen);
        caseGenMapper.updateByPrimaryKeySelective(caseGen);

        // 删除原有图片
        QueryWrapper<DesignSchemeImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cases_id", caseDetailVo.getId());
        imageMapper.delete(queryWrapper);

        // 保存新图片
        List<DesignSchemeImage> images = caseDetailVo.getImages();
        if (images != null && !images.isEmpty()) {
            for (DesignSchemeImage image : images) {
                image.setCasesId(caseDetailVo.getId());
                imageMapper.insert(image);
            }
        }
        return true;
    }

    /**
     * 案例详情
     *
     * @param id
     * @return
     */
    @Override
    public CaseDetailVo queryCase(String id) {
        CaseDetailVo caseDetailVo = new CaseDetailVo();
        Long caseId = Long.parseLong(id);
        CasesGen caseGen = caseGenMapper.selectByPrimaryKey(caseId);
        BeanUtils.copyProperties(caseGen, caseDetailVo);

        // 加载每个方案的图片
        QueryWrapper<DesignSchemeImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cases_id", caseDetailVo.getId());
        List<DesignSchemeImage> designSchemeImages = imageMapper.selectList(queryWrapper);
        caseDetailVo.setImages(designSchemeImages);
        return caseDetailVo;
    }

    /**
     * 案例模糊查询
     *
     * @param caseDetailVo
     * @return
     */
    @Override
    public List<CaseDetailVo> queryCaseByCondition(CaseDetailVo caseDetailVo) {
        List<CaseDetailVo> caseDetailList = new ArrayList<>();
        CasesGenExample caseGenExample = new CasesGenExample();
        CasesGenExample.Criteria criteria = caseGenExample.createCriteria();
        criteria.andAliveFlagEqualTo("1");
        if (caseDetailVo.getCaseName() != null && !caseDetailVo.getCaseName().trim().isEmpty()) {
            criteria.andCaseNameLike("%" + caseDetailVo.getCaseName().trim() + "%");
        }
        if (caseDetailVo.getDesigner() != null) {
            criteria.andDesignerEqualTo(caseDetailVo.getDesigner());
        }
        if (caseDetailVo.getHouseAreaMin() != null && !ObjectUtils.isEmpty(caseDetailVo.getHouseAreaMin())) {
            criteria.andHouseAreaGreaterThanOrEqualTo(caseDetailVo.getHouseAreaMin());
        }
        if (caseDetailVo.getHouseAreaMax() != null && !ObjectUtils.isEmpty(caseDetailVo.getHouseAreaMax())) {
            criteria.andHouseAreaLessThanOrEqualTo(caseDetailVo.getHouseAreaMin());
        }
        if (caseDetailVo.getDesignStyleList() != null && !ObjectUtils.isEmpty(caseDetailVo.getDesignStyleList())) {
            List<String> designStyleList = caseDetailVo.getDesignStyleList();
            criteria.andDesignStyleIn(designStyleList);
        }
        if (caseDetailVo.getCommunityName() != null && !caseDetailVo.getCommunityName().trim().isEmpty()) {
            criteria.andCommunityNameLike("%" + caseDetailVo.getCommunityName() + "%");
        }
        if (!ObjectUtils.isEmpty(caseDetailVo.getFinishDateStart()) && !ObjectUtils.isEmpty(caseDetailVo.getFinishDateEnd())){
            criteria.andFinishDateBetween(caseDetailVo.getFinishDateStart(), caseDetailVo.getFinishDateEnd());
        }
        if (caseDetailVo.getIsRecommende() != null && !ObjectUtils.isEmpty(caseDetailVo.getIsRecommende())) {
            criteria.andIsRecommendeEqualTo(caseDetailVo.getIsRecommende());
        }
        if(caseDetailVo.getDesigner() != null){
            criteria.andDesignerEqualTo(caseDetailVo.getDesigner());
        }
        if (!ObjectUtils.isEmpty(caseDetailVo.getStatus()) && caseDetailVo.getStatus().equals(0)){
            criteria.andStatusEqualTo(0);
        }
        if (!ObjectUtils.isEmpty(caseDetailVo.getStatus()) && caseDetailVo.getStatus().equals(1)){
            criteria.andStatusEqualTo(1);
        }
        // 判断是否需要根据推荐值排序
        if(!ObjectUtils.isEmpty(caseDetailVo.getIsSorting()) && caseDetailVo.getIsSorting().equals("1")){
            caseGenExample.setOrderByClause("recommende_value ASC");
        }
        // 3. 查询分页数据
//        PageHelper.startPage(caseDetailVo.getPageNum(), caseDetailVo.getPageSize());
        List<CasesGen> caseGens = caseGenMapper.selectByExample(caseGenExample);
        if (!ObjectUtils.isEmpty(caseGens)){
            BeanUtil.copyListProperties(caseGens, caseDetailList, CaseDetailVo.class);
//            for (int i = 0; i < caseGens.size(); i++) {
//                CaseDetailVo caseDetailVo1 = new CaseDetailVo();
//                BeanUtil.copyProperties(caseGens.get(i),caseDetailVo1);
//                String designStyleCode = caseGens.get(i).getDesignStyle();
//                if (!ObjectUtils.isEmpty(designStyleCode)){
//                    // 1. 去除首尾的方括号
//                    String content = designStyleCode.substring (1, designStyleCode.length () - 1);
//                    // 2. 按逗号分割，去除空格，收集为 List<String>
//                    List<String> result = Arrays.stream (content.split (","))
//                            .map (String::trim) // 去除每个元素的前后空格
//                            .collect (Collectors.toList ()); // 收集为 List<String>
//                    caseDetailVo1.setDesignStyle(result);
//                    caseDetailList.add(i,caseDetailVo1);
//                }else {
//                    caseDetailList.add(i,caseDetailVo1);
//                }

            }
        return caseDetailList;

    }

    @Override
    @Transactional
    public boolean addCase(CaseDetailVo vo) {
        if (vo.getDesigner() == null || ObjectUtils.isEmpty(vo.getDesignerName())){
            log.info("!!!新增案例必须关联设计师信息!!!");
            return false;
        }
        CasesGen casesGen = new CasesGen();
        BeanUtils.copyProperties(vo,casesGen);
        casesGen.setAliveFlag("1");
//        caseGenMapper.insert(casesGen);
        try{
            caseGenMapper.insertSelective(casesGen);
        }catch (Exception e){
            log.info("获取当前新增案例##异常##", e);
            return false;
        }

        // 保存图片
        List<DesignSchemeImage> images = vo.getImages();
        if (images != null && !images.isEmpty()) {
            for (DesignSchemeImage image : images) {
                image.setCasesId(casesGen.getId());
                imageMapper.insert(image);
            }
        }
        return true;
    }

    @Override
    public boolean deleteCaseById(Long id) {
        CasesGen casesGen = new CasesGen();
        casesGen.setId(id);
        casesGen.setAliveFlag("0");
        try{
            caseGenMapper.updateByPrimaryKeySelective(casesGen);
        }catch (Exception e){
            log.info("获取当前逻辑删除案例##异常##", e);
            return false;
        }
        return true;
    }

    @Override
    public List<CaseDetailVo> queryCaseByDesignerId(Long id) {
        List<CaseDetailVo> caseDetailVoList = new ArrayList<>();
        CasesGenExample casesGenExample = new CasesGenExample();
        casesGenExample.createCriteria().andDesignerEqualTo(id).andAliveFlagEqualTo("1");
        List<CasesGen> casesGenList = caseGenMapper.selectByExample(casesGenExample);
        if (!ObjectUtils.isEmpty(casesGenList)){
            BeanUtil.copyListProperties(casesGenList,caseDetailVoList, CaseDetailVo.class);
        }
        return caseDetailVoList;
    }

    @Override
    public IPage<CaseDetailVo> queryCaseByPage(CaseDetailVo vo) {
        // 1. 构建 MyBatis-Plus 分页对象（传入 pageNum/pageSize）
        Page<CasesGen> page = new Page<>(vo.getPageNum(), vo.getPageSize());

        // 2. 调用 Mapper 分页查询（MyBatis-Plus 自动处理 limit）
        IPage<CasesGen> caseGenPage = caseGenMapper.selectCasePage(page, vo);

        // 3. 转换：CasesGen → CaseDetailVo（批量转换，避免循环 new 对象）
        List<CaseDetailVo> caseDetailList = new ArrayList<>();
        Map<Long, List<DesignSchemeImage>> caseImageMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(caseGenPage.getRecords())) {
            BeanUtil.copyListProperties(caseGenPage.getRecords(), caseDetailList, CaseDetailVo.class);

            // 4. 批量加载图片列表（避免 N+1 问题：先查所有案例ID，再批量查图片）
            List<Long> caseIds = caseGenPage.getRecords().stream()
                    .map(CasesGen::getId).collect(Collectors.toList());
            // 4.1 批量查询图片（按案例ID分组）
            caseImageMap = getCaseImageMap(caseIds);
            // 4.2 给每个 CaseDetailVo 赋值图片列表
            for (CaseDetailVo detailVo : caseDetailList) {
                detailVo.setImages(caseImageMap.getOrDefault(detailVo.getId(), new ArrayList<>()));
            }
        }

        // 5. 构建分页结果：复用原分页元数据（总条数、总页数），替换数据列表
        Map<Long, List<DesignSchemeImage>> finalCaseImageMap = caseImageMap;
        return caseGenPage.convert(caseGen -> {
            CaseDetailVo detailVo = new CaseDetailVo();
            BeanUtils.copyProperties(caseGen, detailVo);
            // 补充图片列表（从上面的 map 中获取）
            detailVo.setImages(finalCaseImageMap.getOrDefault(caseGen.getId(), new ArrayList<>()));
            return detailVo;
        });
    }

    /**
     * 辅助方法：批量查询案例图片，按案例ID分组（避免 N+1 问题）
     */
    private Map<Long, List<DesignSchemeImage>> getCaseImageMap(List<Long> caseIds) {
        Map<Long, List<DesignSchemeImage>> imageMap = new HashMap<>();
        if (CollectionUtils.isEmpty(caseIds)) {
            return imageMap;
        }
        // 批量查询所有案例的图片
        List<DesignSchemeImage> allImages = imageMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<DesignSchemeImage>()
                        .in("cases_id", caseIds)
        );
        // 按案例ID分组
        for (DesignSchemeImage image : allImages) {
            imageMap.computeIfAbsent(image.getCasesId(), k -> new ArrayList<>()).add(image);
        }
        return imageMap;
    }
}
